import React, { useState } from "react";
import { Card, Button, Space, Tag, Typography, Input, Divider } from "antd";
import { useRequest } from "ahooks";
import { history } from "umi";

const { Text, Paragraph } = Typography;

// 模拟 API 请求
const fetchUserData = (
  id: number
): Promise<{ id: number; name: string; email: string; fetchTime: string }> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id,
        name: `用户${id}`,
        email: `user${id}@example.com`,
        fetchTime: new Date().toLocaleTimeString(),
      });
    }, 1000);
  });
};

const CachePage: React.FC = () => {
  const [userId, setUserId] = useState(1);

  const { data, loading, error, run } = useRequest(fetchUserData, {
    manual: true,
    cacheKey: `user-${userId}`, // 缓存键
    staleTime: 5000, // 数据保持新鲜时间 5 秒
  });

  return (
    <div style={{ padding: "24px" }}>
      <Button
        onClick={() => history.push("/")}
        style={{ marginBottom: "16px" }}
      >
        返回首页
      </Button>

      <Card title="useRequest 缓存 (cacheKey)" style={{ marginBottom: "16px" }}>
        <Paragraph>
          <Text strong>功能说明：</Text> 测试 cacheKey
          参数，相同缓存键的请求会使用缓存数据，避免重复请求。
        </Paragraph>

        <Space direction="vertical" style={{ width: "100%" }}>
          <div>
            <Text strong>状态：</Text>
            {loading && <Tag color="processing">加载中...</Tag>}
            {error && <Tag color="error">错误: {error.message}</Tag>}
            {data && <Tag color="success">成功</Tag>}
            <Tag color="blue">缓存键: user-{userId}</Tag>
          </div>

          <Space>
            <Text>用户ID：</Text>
            <Input
              type="number"
              value={userId}
              onChange={(e) => setUserId(Number(e.target.value) || 1)}
              style={{ width: 100 }}
            />
            <Button
              type="primary"
              onClick={() => run(userId)}
              loading={loading}
            >
              获取用户数据
            </Button>
          </Space>

          <Divider />

          <div>
            <Text strong>测试说明：</Text>
            <ul>
              <li>点击"获取用户数据"按钮获取数据</li>
              <li>再次点击相同用户ID的按钮，会使用缓存数据（不会重新请求）</li>
              <li>切换用户ID后点击，会发起新的请求</li>
              <li>缓存数据在 5 秒内保持新鲜</li>
            </ul>
          </div>

          {data && (
            <div>
              <Text strong>用户数据：</Text>
              <div style={{ marginTop: "8px" }}>
                <p>ID: {data.id}</p>
                <p>姓名: {data.name}</p>
                <p>邮箱: {data.email}</p>
                <p>获取时间: {data.fetchTime}</p>
              </div>
            </div>
          )}
        </Space>
      </Card>
    </div>
  );
};

export default CachePage;
